{% extends "templates/main_template.html.j2" %}

{% import "macros/issues_table.html.j2" as ISSUES_TABLE %}
{% import "macros/markdown_textarea.html.j2" as MARKDOWN_TEXTAREA %}
{% import "macros/tab_switcher.html.j2" as TAB_SWITCHER %}
{% import "macros/modal_confirmation.html.j2" as CONFIRMATION %}
{% import "macros/user_name.html.j2" as USER_NAME %}
{% import "macros/date_range_picker.html.j2" as DATE_RANGE_PICKER %}

{% block title %}{{ target_project.caption|e }} · Проект · Farado{% endblock %}

{% set active_menu = 'projects' %}
{% set issues_count = project_manager.project_issues_count(target_project.id) %}
{% set tab_menu = [
  ['Запросы [' + issues_count|string + ']', 'issues'],
  ['О проекте', 'about'],
  ['Версии [' + target_project.versions|length|string + ']', 'versions'],
  ['Отчёт', 'report'],
] %}


{#----------------------------------------------------------------------------#}
{% block styles %}
  {{ ISSUES_TABLE.STYLES() }}
  <link href="/static/css/page-toolbar.css" rel="stylesheet" type="text/css" />
  {{ DATE_RANGE_PICKER.STYLES() }}
  {{ MARKDOWN_TEXTAREA.STYLES() }}
{% endblock %}


{#----------------------------------------------------------------------------#}
{% block breadcrumb %}
  <ol class="breadcrumb">
    <li class="breadcrumb-item active" aria-current="page">
      {{ target_project.caption|e }}
    </li>
  </ol>
{% endblock %}


{#----------------------------------------------------------------------------#}
{# Таб 1 — Запросы #}
{% block tab_content_1 %}
  {% if target_project %}
      {# TODO Перенести кнопку создания запроса в подходящее место #}
      <div class="page-toolbar">
        <button
            class="btn btn-outline-primary btn-sm dropdown-toggle"
            type="button"
            id="dropdownMenuAddIssue"
            data-bs-toggle="dropdown"
            aria-expanded="false">Создать запрос</button>
        <ul class="dropdown-menu" aria-labelledby="dropdownMenuAddIssue">
          {% for issue_kind in project_manager.issue_kinds() -%}
            {% set workflow = project_manager.workflow(issue_kind.workflow_id) %}
            <li>
              <a  class="dropdown-item"
                  href="/issues/add_issue/{{ issue_kind.id }}?project_id={{ target_project.id }}">
                {{- workflow.caption|e }}: {{ issue_kind.caption|e -}}
              </a>
            </li>
          {%- endfor %}
        </ul>
      </div> 

    <div class="table-container">
      {{ ISSUES_TABLE.TAG(columns, column_helper) }}
    </div>
  {% endif %}
{% endblock tab_content_1 %}


{#----------------------------------------------------------------------------#}
{# Таб 2 — О проекте #}
{% block tab_content_2 %}
  <div class="row">

    <div class="col">
      <!--reserved-->
    </div>

    <!-- Project view/edit switch -->
    <div class="col">
      <ul class="nav nav-pills mb-3 justify-content-end" id="pillsTab" role="tablist">
        <li class="nav-item" role="presentation">
          <button
              class="nav-link active"
              id="pills-view-tab"
              data-bs-toggle="pill"
              data-bs-target="#pills-view"
              type="button"
              role="tab"
              aria-controls="pills-view"
              aria-selected="true">Просмотр</button>
        </li>
        <li class="nav-item" role="presentation">
          <button
              class="nav-link {% if not restriction.is_save_enabled %}disabled{% endif %}"
              id="pills-edit-tab"
              data-bs-toggle="pill"
              data-bs-target="#pills-edit"
              type="button"
              role="tab"
              aria-controls="pills-edit"
              {% if not restriction.is_save_enabled %}disabled{% endif %}
              aria-selected="false">Редактор</button>
        </li>
      </ul>
    </div>
  </div>

  <div class="row placeholders issue-content">
    <div class="tab-content" id="pillsTabContent">
      <!-- VIEW -->
      <div
          class="tab-pane fade show active"
          id="pills-view"
          role="tabpanel"
          aria-labelledby="pills-view-tab">

        <!-- Project.content -->
        <div class="col-12">
          <div id="contentView"
              class="comment-link markdown_result_container"></div>
        </div>
      </div>

      <!-- EDIT -->
      <div
          class="tab-pane fade"
          id="pills-edit"
          role="tabpanel"
          aria-labelledby="pills-edit-tab">

        <form class="row g-3" action="/projects/project/{{ target_project.id }}" method="post">

          <!-- Project.caption -->
          <div class="col-12">
            <label for="inputCaption" class="form-label">Название проекта</label>
            <input type="text" name="target_project_caption" class="form-control" id="inputCaption" value="{{ target_project.caption|e }}" required>
          </div>

          <!-- Project.content -->
          <div class="col-12">
            <label for="contentTab" class="form-label">Описание</label>
            {{ MARKDOWN_TEXTAREA.INPUT(
                  tab_id='contentTab',
                  result_id='target_project_content_result',
                  field_name='target_project_content',
                  field_value=target_project.content|e )
            }}
          </div>

          <!-- Project.issues_view_settings -->
          <div class="col-12">
            <label for="input_issues_view_settings" class="form-label">Просмотр настроек запросов</label>
            {# TODO поле ввода заменить на адекватный ui позволяющий выбрать столбцы таблицы с issues #}
            <input
                type="text"
                name="target_project_issues_view_settings"
                class="form-control"
                id="input_issues_view_settings"
                value="{{ target_project.issues_view_settings }}">
          </div>

          {% if restriction.is_save_enabled %}
            <div class="col-12">
              <div class="clearfix">
                {# -- Кнопка: удалить -- #}
                  {{ CONFIRMATION.BUTTON(
                      caption = '<i class="bi bi-trash"></i> Удалить',
                      title = 'Удалить данный проект',
                      class = 'btn btn-danger ml-3 float-start',
                      target = 'remove_project_confirmation_'
                          + target_project.id|string)
                  }}
                  {{ CONFIRMATION.MODAL_WINDOW(
                      title = 'Удаление проекта',
                      text = 'Вы уверены, что хотите навсегда удалить проект «'
                          + target_project.caption|e
                          + '»?',
                      action_button_href = '/projects/remove_project/'
                          + target_project.id|string,
                      action_button_text = 'Да',
                      window_id = 'remove_project_confirmation_'
                          + target_project.id|string)
                  }}
                {# -- /Кнопка: удалить -- #}

                {# -- Кнопка: сохранить -- #}
                  <button
                      type="submit"
                      id="saveButton"
                      class="btn btn-success float-end">
                    <i class="bi bi-save"></i> Сохранить
                  </button>
                {# -- /Кнопка: сохранить -- #}
              </div>
            </div>
          {% endif %}

        </form>
      </div>
    </div>
  </div>
{% endblock tab_content_2 %}


{#----------------------------------------------------------------------------#}
{# Таб 3 — Версии #}
{% block tab_content_3 %}
  {% if target_project %}
    <div class="page-toolbar">
      {# TODO Перенести кнопку создания версии в подходящее место #}
      <a href="/projects/add_version/{{ target_project.id }}"
          class="btn btn-outline-primary btn-sm"
          role="button"
          aria-pressed="true">Создать версию</a>
    </div>

    <br/>

    <div class="table-container">
      <table
          class="table table-striped table-sm table-bordered table-hover"
          style="width:100%"
          id="versions_table">
        <thead>
          <tr>
            <th scope="col" style="width: 1%">№</th>
            <th scope="col">Наименование</th>
            <th scope="col">Дата начала</th>
            <th scope="col">Дата выпуска</th>
            <th scope="col">Состояние</th>
          </tr>
        </thead>
        <tbody>
          {% for version in target_project.versions %}
          <tr>
            <th scope="row">{{ version.id }}</th>
            <td>
              <a href="/projects/version/{{ version.id }}">{{ version.caption|e }}</a>
            </td>
            <td>{{ version.start_date }}</td>
            <td>{{ version.release_date }}</td>
            <td>
              {%- set version_state = version.state() -%}
              {%- set VersionStates = version.version_states() -%}
              {%- if version_state == VersionStates.not_started -%}
                В планах
              {%- elif version_state == VersionStates.in_progress -%}
                В работе
              {%- elif version_state == VersionStates.released -%}
                Выпущена
              {%- else -%}
                Неверные даты
              {%- endif -%}
            </td>
          </tr>
          {% endfor %}
        </tbody>
        <tfoot>
          <tr>
            <th>№</th>
            <th>Наименование</th>
            <th>Дата начала</th>
            <th>Дата выпуска</th>
            <th>Состояние</th>
          </tr>
        </tfoot>
      </table>
    </div>
  {% endif %}
{% endblock tab_content_3 %}


{#----------------------------------------------------------------------------#}
{# Таб 4 — Отчёт #}
{% block tab_content_4 %}
  {% if target_project %}
    <div class="row mt-2">
      <div class="col">
        <form
            id="report_form"
            action="/projects/report/{{ target_project.id }}"
            method="post">
          {{ DATE_RANGE_PICKER.INPUT(
                from_date=from_date,
                to_date=to_date,
                id="daterange",
                name="daterange")
          }}
        </form>
      </div>
    </div>

    <br/>

    {% if report_data %}
      <div class="accordion" id="accordion_timeline_diagramm">
        <div class="accordion-item">
          <h2 class="accordion-header" id="headingOne">
            <button
                class="accordion-button"
                type="button"
                data-bs-toggle="collapse"
                data-bs-target="#collapseOne"
                aria-expanded="true"
                aria-controls="collapseOne">
              Временная шкала
            </button>
          </h2>
          <div
              id="collapseOne"
              class="accordion-collapse collapse show"
              aria-labelledby="headingOne"
              data-bs-parent="#accordion_timeline_diagramm">
            <div class="accordion-body">
              <div class="col">
                <div id="timeline_diagramm_div"></div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="table-container">
        <table
            class="table table-striped table-sm table-bordered table-hover"
            style="width:100%"
            id="report_table">
          <thead>
            <tr>
              <th scope="col">Сотрудник</th>
              <th scope="col">Начало работ</th>
              <th scope="col">Окончание работ</th>
              <th scope="col">Тип запроса</th>
              <th scope="col">Состояние</th>
              <th scope="col">Сейчас</th>
              <th scope="col">Запрос</th>
              <th scope="col">Предок</th>
            </tr>
          </thead>
          <tbody>
            {% for item in report_data.container %}
              {% set issue = project_manager.issue(item.issue_id)%}
              {% set state = project_manager.state(item.state_id) %}
              {% set target_user = project_manager.user(item.user_id)%}

              {% if issue and target_user %}
                {% set actual_state = project_manager.state(issue.state_id) %}
                {% set issue_kind = project_manager.issue_kind(issue.issue_kind_id) %}
                {% set workflow = project_manager.workflow(issue_kind.workflow_id) %}
                {% set parent_issue = project_manager.issue(issue.parent_id) %}

                <tr>
                  <td>
                    <a href="/users/user_statistics/{{ target_user.id }}">
                      {{ USER_NAME.VALUE(target_user) }}
                    </a>
                  </td>
                  <td style="white-space: nowrap;">{{ item.from_value() }}</td>
                  <td style="white-space: nowrap;">{{ item.to_value() }}</td>
                  <td>{{ workflow.caption|e }}: {{ issue_kind.caption|e }}</td>
                  <td>{{ state.caption|e }}</td>
                  <td>{{ actual_state.caption|e }}</td>
                  <td>
                    <a href="/issues/issue/{{ issue.id }}"
                        title="{{ issue.caption|e }}">
                      #{{ issue.id }}: {{ issue.caption|e }}
                    </a>
                  </td>
                  <td>
                    {% if parent_issue %}
                      <a href="/issues/issue/{{ parent_issue.id }}"
                          title="{{ parent_issue.caption|e }}">
                        #{{ parent_issue.id }}: {{ parent_issue.caption|e }}
                      </a>
                    {% endif %}
                  </td>
                </tr>
              {% endif %}
            {% endfor %}
          </tbody>
          <tfoot>
            <tr>
              <th>Сотрудник</th>
              <th>Начало работ</th>
              <th>Окончание работ</th>
              <th>Тип запроса</th>
              <th>Состояние</th>
              <th>Сейчас</th>
              <th>Запрос</th>
              <th>Предок</th>
            </tr>
          </tfoot>
        </table>
      </div>
    {% endif %}

  {% endif %}
{% endblock tab_content_4 %}


{#----------------------------------------------------------------------------#}
{% block content %}
{% endblock %}


{#----------------------------------------------------------------------------#}
{% block scripts %}
  {{ MARKDOWN_TEXTAREA.SCRIPTS() }}
  {{ ISSUES_TABLE.SCRIPTS() }}
  {{ DATE_RANGE_PICKER.SCRIPTS() }}

  <script src="/static/js/apexcharts/apexcharts.min.js"></script>

  <script>
    document_ready_function = function() {
      {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('pillsTab') }}
      {{ TAB_SWITCHER.DOCUMENT_READY_SCRIPT('contentTab') }}

      {% if target_project %}
        {{ ISSUES_TABLE.DOCUMENT_READY_SCRIPT(
            columns,
            column_helper,
            url="/projects/project_issues_data/" + target_project.id | string)
        }}

        $('#versions_table').DataTable({
          "paging": false,
          "fixedColumns": true,
          "processing": true,
          "serverSide": false,
          "ordering": true,
          "order": [[ 1, "asc" ]]
        });

        {% if report_data %}
          $('#report_table').DataTable({
            "paging": false,
            "fixedColumns": true,
            "processing": true,
            "serverSide": false,
            "ordering": true,
            "order": [[ 0, "asc" ]],
            "autoWidth": false,
            "columnDefs": [
              { "width": "2%", "targets": 1 },
              { "width": "2%", "targets": 2 }
            ]
          });

          {%- set report_data_length = report_data.issues_ids()|length -%}
          {% if report_data_length %}
            var timeline_diagramm_options = {
              series: [
                {% set container_by_user = report_data.container_by_user() %}
                {% for user_id in container_by_user.keys() %}
                  {% set current_user = project_manager.user(user_id)%}
                  {% set items = container_by_user[user_id]%}
                  {% if current_user %}
                    {
                      name: '{{ USER_NAME.VALUE(current_user) }}',
                      data: [
                        {% for item in items %}
                          {% set issue = project_manager.issue(item.issue_id) %}
                          {% set state = project_manager.state(item.state_id) %}
                          {
                            x: '#{{ issue.id }} {{ issue.caption|e }}',
                            y: [
                              new Date('{{ item.from_value() }}').getTime(),
                              new Date('{{ item.to_value() }}').getTime()
                            ]
                          }
                          {%- if not loop.last %},{% endif -%}
                        {% endfor %}
                      ]
                    }
                    {%- if not loop.last %},{% endif -%}
                  {% endif %}
                {% endfor %}
              ],
              chart: {
                height:
                  {%- if     5 > report_data_length -%}  200
                  {%- elif  10 > report_data_length -%}  400
                  {%- elif  20 > report_data_length -%}  500
                  {%- elif  30 > report_data_length -%}  600
                  {%- elif  40 > report_data_length -%}  800
                  {%- elif  80 > report_data_length -%} 1000
                  {%- elif 160 > report_data_length -%} 2000
                  {%- elif 320 > report_data_length -%} 3000
                  {%- elif 640 > report_data_length -%} 4000
                  {%- else                          -%} 6000
                  {%- endif -%},
                type: 'rangeBar'
              },
              plotOptions: {
                bar: {
                  horizontal: true,
                  barHeight: '90%',
                  rangeBarGroupRows: true
                }
              },
              xaxis: {
                type: 'datetime',
                position: 'top',
                labels: {
                  format: 'dd.MM.yyyy',
                }
              },
              yaxis: {
                labels: {
                  align: 'left',
                  minWidth: 0,
                  maxWidth: 160
                }
              },
              legend: {
                position: 'right'
              },
              grid: {
                row: {
                  colors: ['#f3f4f5', '#fff'],
                  opacity: 1
                }
              },
              fill: {
                type: 'solid',
                opacity: 0.6
              }
            };

            var timeline_diagramm = new ApexCharts(
              document.querySelector("#timeline_diagramm_div"),
              timeline_diagramm_options
            );
            timeline_diagramm.render();
          {% endif %}
        {% endif %}

        {{ DATE_RANGE_PICKER.DOCUMENT_READY_SCRIPT(
              input_id="daterange",
              form_id="report_form")
        }}
      {% endif %}

      markdownToHtml('target_project_content', 'contentView');
      markdownToHtml('target_project_content', 'target_project_content_result');

      {% if restriction.is_save_enabled and is_edit_mode %}
        /* {# Автоматический переход на вкладку редактирования проекта
              после загрузки страницы #} */
        var tab = new bootstrap.Tab(document.querySelector('#pills-edit-tab'));
        tab.show();
      {% endif %}
    }
  </script>
{% endblock %}
